#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext.webapp.util import run_wsgi_app
import logging
import time
import datetime
import os
import oauth
import simplejson
import urllib
import urllib2
import random
import sys
q
"""

"""
class mixiGraphCallBack(webapp.RequestHandler):
    
    
    def get(self):
        c = consumer_keys("./lib/data/key.json")
        CONSUMER_KEY = c["mixi"]["consumer_key"]
        CONSUMER_SECRET_KEY = c["mixi"]["consumer_secret_key"]
        """grant_type    “authorization_code”
        client_id    Consumer key
        client_secret    Consumer secret
        code    Authorization Code
        redirect_uri    Redirect URI （サービス登録の際に入力したURIをそのまま指定します）"""
        url = 'https://secure.mixi-platform.com/2/token'
        token_params = {
                        'grant_type'    : 'authorization_code',
                        'client_id'     : CONSUMER_KEY,
                        'client_secret' : CONSUMER_SECRET_KEY,
                        'code'          : self.request.get("code"),
                        'redirect_uri'  : 'http://%s/redirect' % os.environ["HTTP_HOST"]
        }
        
        token_res = urllib.urlopen(
             url,
             urllib.urlencode(token_params).encode("utf-8")
             ).read()
        token_dic = simplejson.loads(token_res)
        memcache.set("oauth",token_dic)
        self.response.headers['Content-Type'] = 'text/html;charset=utf-8'
        #print token_res
        expires_date = datetime.datetime.utcnow() + datetime.timedelta(900)
        expires = expires_date.strftime("%d %b %Y %H:%M:%S GMT")
        for i in token_dic:
            self.response.headers.add_header('Set-Cookie', '%s=%s; expires=%s' % (i, token_dic[i], expires))
            #self.response.out.write(token_dic[i])
        self.redirect('/')
        

application = webapp.WSGIApplication([('/redirect', mixiGraphCallBack)], debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
